package com.kinon.ceshiaccount.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.bean.LoginBean;
import com.kinon.ceshiaccount.bean.UrlBean;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.bean.urgent.U_SettletmentBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.MyCallback;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.network.http.HttpApiUrl;
import com.kinon.ceshiaccount.service.GetMakemealService;
import com.kinon.ceshiaccount.sunmi.SunmiSdkManage;
import com.kinon.ceshiaccount.sunmi.constatus.SunmiImgPath;
import com.kinon.ceshiaccount.sunmi.util.SharedPreferencesUtil;
import com.kinon.ceshiaccount.util.AppInfoUtil;
import com.kinon.ceshiaccount.util.ImgDonwloads;
import com.kinon.ceshiaccount.util.MyShowDialog;
import com.kinon.ceshiaccount.util.SPManage;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;
import sunmi.ds.DSKernel;
import sunmi.ds.callback.IConnectionCallback;

import static com.kinon.ceshiaccount.sunmi.constatus.SunmiImgPath.WELCOME_IMG_ID;

/**
 * Created by luohao on 2017-06-29.
 * 登录
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener,
        View.OnFocusChangeListener {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    /**
     * 用户登录类型
     */
    private final String USER_LOGIN_TYPE = "3";
    DSKernel mDSKernel;// SDK核心类
    long taskId;
    private TextInputLayout til_account;
    private TextInputEditText et_accountNum;
    private TextInputLayout til_pwd;
    private TextInputEditText et_password;
    private Button btn_login;
    private Button btn_urgentLogin;
    private TextView tv_appSersion;
    private String sunmiSN = "";
    private int errorNum = 0;
    private String serverUrl = "";
    private TextWatcher tWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };
    private IConnectionCallback mConnCallback = new IConnectionCallback() {
        @Override
        public void onDisConnect() {
        }

        @Override
        public void onConnected(final ConnState state) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    Mtoast("state:"+state);
                    switch (state) {
                        case AIDL_CONN:
                            //与本地service的连接畅通
                            break;
                        case VICE_SERVICE_CONN:
                            //与副屏service连接畅通
                            long fileId = SharedPreferencesUtil.getLong(getApplicationContext(),
                                    WELCOME_IMG_ID);
                            //判断文件是否存在
                            if (fileId != -1L) SunmiSdkManage.getInstance()
                                    .checkImg(getApplicationContext(),
                                            fileId, WELCOME_IMG_ID);
                            SunmiSdkManage.getInstance().showWelcomeImg();
                            break;
                        case VICE_APP_CONN:
                            //与副屏app连接畅通
                            break;
                    }
                }
            });
        }
    };


    //    @Override
//    protected void onReadPhoneStatePermission() {
//        super.onReadPhoneStatePermission();
//        CustomDialog dialog=new CustomDialog(getApplicationContext(),
//                "是否去设置页面开启权限", new CustomDialog.DialogClickListener() {
//            @Override
//            public void onDialogClick(int btn) {
//                if(btn==1){
//                    //跳到应用设置页面
//                    goToAppSetting();
//                }
//            }
//        });
//        dialog.show();
//    }
//    private void goToAppSetting(){
//        Intent intent = new Intent();
//        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//        Uri uri = Uri.fromParts("package", getPackageName(), null);
//        intent.setData(uri);
//        startActivityForResult(intent, 123);
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_layout);
//        isPermission();
        verifyStoragePermissions(this);
        initView();
        isgetUrl();
        initSDK();

//        getSN();


    }

    public void verifyStoragePermissions(Activity activity) {
        try {
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        Constant.IS_OPEN_VOICE = SPManage.getInstance().getBoolen("IS_OPEN_VOICE");
        Constant.TIME_SCREEN_JUMP = SPManage.getInstance().getInt("TIME_SCREEN_JUMP", 100);
        Constant.CARD_LENGTH = SPManage.getInstance().getInt("CARD_LENGTH", 8);
        til_account = (TextInputLayout) findViewById(R.id.til_account);
        et_accountNum = (TextInputEditText) findViewById(R.id.et_accountNum);
        til_pwd = (TextInputLayout) findViewById(R.id.til_pwd);
        et_password = (TextInputEditText) findViewById(R.id.et_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_urgentLogin = (Button) findViewById(R.id.btn_urgentLogin);
        tv_appSersion = (TextView) findViewById(R.id.tv_appSersion);

        tv_appSersion.setText("版本号：" + AppInfoUtil.getVersionName());

//        btn_urgentLogin.setVisibility(View.GONE);

        et_accountNum.setText(SPManage.getInstance().getString("loginaccoun"));
        et_password.setText(SPManage.getInstance().getString("loginpwd"));

        btn_login.setOnClickListener(this);
        btn_urgentLogin.setOnClickListener(this);
        et_accountNum.setOnFocusChangeListener(this);
        et_password.setOnFocusChangeListener(this);

    }

    private void initSDK() {

        SunmiSdkManage.getInstance()
                .sunmiInit(LoginActivity.this, mConnCallback);
    }

    @Override
    public void onClick(View view) {
        hideKeyboard();
        switch (view.getId()) {
            case R.id.btn_login:
                //登录
                login();
                break;
            case R.id.btn_urgentLogin:
                //紧急模式
                urgentLogin();
                break;
        }
    }

    /**
     * 紧急状态登录
     */
    private void urgentLogin() {
        Constant.URGENT_TYPE = true;
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        finish();

    }

    /**
     * 开启获取取餐信息的服务
     */
    private void startAllService() {

        Intent intent = new Intent(this, GetMakemealService.class);
        startService(intent);

//
    }

    //是否下载图片
    private void isDownloadImg(ArrayList<LoginBean.Pic> getPic) {
        if (getPic != null && getPic.size() > 0
                && ((!getPic.get(0).getPic().equals(SPManage.getInstance().getString("adimgurl")))
                || !(new File(SunmiImgPath.pathwelcom).exists()))) {
            SunmiSdkManage.getInstance().deleteFileExist(SharedPreferencesUtil.getLong(getApplicationContext(),
                    WELCOME_IMG_ID));
            String adimgurl = getPic.get(0).getPic();
            SPManage.getInstance().putCommit("adimgurl", adimgurl);
            //下载图片
            ImgDonwloads.donwloadImg(LoginActivity.this, adimgurl);

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        stopService(intent2);
    }

    /**
     * 判断是否要获得url
     */
    private void isgetUrl() {
        if (!SPManage.getInstance().getBoolen("isdeletesp")) {
            SPManage.getInstance().removesp();
            SPManage.getInstance().putBCommit("isdeletesp", Constant.IS_DELETE_SP);
//            Constant.IS_DELETE_SP=false;
        }
        serverUrl = SPManage.getInstance().getString("serverUrl");
        if (TextUtils.isEmpty(serverUrl)) {
            getUrl();
        } else {
            HttpApiUrl.serverUrl = serverUrl;
            //获取取餐信息
            startAllService();
        }
    }

    /**
     * 获取后面请求的URL地址
     */
    private void getUrl() {
        if (errorNum >= 3) {
            Mtoast("获取本机信息失败，请关闭APP重新进入！");
            return;
        }
        //获得SN

//        Log.e(TAG, "serialNum=="+serialNum);
        Call<BaseBean<UrlBean>> call = HttpManage.getRequestUrlApi().getByMachine(AccountApplication.serialNum);
        call.enqueue(new MyCallback<BaseBean<UrlBean>>() {
            @Override
            public void onSuccess(Call<BaseBean<UrlBean>> call,
                                  Response<BaseBean<UrlBean>> response) {
                BaseBean<UrlBean> bean = response.body();
                serverUrl = bean.getData().getApi();
                Gson gson = new Gson();
                String urlbean = gson.toJson(bean.getData());
                SPManage.getInstance().putCommit("urlbean", urlbean);
                SPManage.getInstance().putCommit("screenSize", bean.getData().getSize());
                if (bean.getData().getCard() == 0) {
                    SPManage.getInstance().putICommit("CARD_LENGTH", 8);
                    Constant.CARD_LENGTH = bean.getData().getCard();
                } else {
                    SPManage.getInstance().putICommit("CARD_LENGTH", bean.getData().getCard());
                    Constant.CARD_LENGTH = bean.getData().getCard();
                }
                if (!TextUtils.isEmpty(serverUrl)) {
                    HttpApiUrl.serverUrl = serverUrl;
                    bean.getData().getApp_function();
                    SPManage.getInstance().putCommit("serverUrl", serverUrl);
                    SPManage.getInstance().putCommit("back_url", bean.getData().getBack_url());
                }
            }

            @Override
            public void onError(int code, String error) {
                errorNum++;
                getUrl();
            }
        });

    }

    /**
     * 登录方法
     */
    private void login() {
        String accoun = til_account.getEditText().getText().toString().trim();
        if (TextUtils.isEmpty(accoun)) {
            til_account.setError(getResources().getString(R.string.hint_accountNum));
            return;
        }
        String password = til_pwd.getEditText().getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            til_pwd.setError(getResources().getString(R.string.hint_password));
            return;
        }
        Log.e(TAG, "login-HttpApiUrl==" + HttpApiUrl.serverUrl);
        if (TextUtils.isEmpty(serverUrl)) {
            Mtoast("获取本机信息失败，请关闭APP重新进入！");
//            Mtoast("登录失败");
//            getUrl();
//            errorNum=0;
            return;
        }
        MyShowDialog.showLoadingDialog(LoginActivity.this, "登录中....");
        logincallback(accoun, password);
    }

    /**
     * 登录返回
     */
    private void logincallback(final String accoun, final String password) {
        int num = DataSupport.where("submit = ?", "0").count(U_SettletmentBean.class);
        String serialNum = android.os.Build.SERIAL;
        Call<String> call1 = HttpManage.getRequestApi().
                login(accoun, password, USER_LOGIN_TYPE, num, AppInfoUtil.getVersionName(), serialNum);
        call1.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {
                MyShowDialog.closeLoadingDialog();
                Gson gson = new Gson();
                LoginBean login = gson.fromJson(data, LoginBean.class);
                isDownloadImg(login.getPic());

                SPManage.getInstance().putCommit("loginaccoun", accoun);
                SPManage.getInstance().putCommit("loginpwd", password);
                SPManage.getInstance().putCommit("token", login.getToken());
                Constant.ACCESS_PAY_TYPE = login.getAccess();
//                Gson gson=new Gson();
                String roles = gson.toJson(login.getRoles());
                SPManage.getInstance().putCommit("roles", roles);

                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onError(int code, String error) {
                MyShowDialog.closeLoadingDialog();
                Mtoast(error);
            }
        });
    }

    private void hideKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                    hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onFocusChange(View view, boolean b) {

        switch (view.getId()) {
            case R.id.et_accountNum:
                if (b) {
                    til_account.setErrorEnabled(false);
                }

                break;
            case R.id.et_password:
                if (b) {
                    til_pwd.setErrorEnabled(false);
                } else {
                    if (et_accountNum.getText().toString().trim().length() == 0) {
                        til_account.setErrorEnabled(true);
                    }
                }
                break;
        }
    }
}
